package com.blog.wu.myblog.activemq.subscribe;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @Author wuyanshen
 * @Date 2018-12-25 1:33 PM
 * @Discription 发布订阅通讯 一对多 可以有多个消费者 原生方式activeMQ 消费者
 */
public class ActiveMqConsumer {

    public static void main(String[] args) {

        try {
            //获取mq连接工厂
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, "tcp://127.0.0.1:32768");
            //创建连接
            Connection connection = connectionFactory.createConnection();
            //启动连接
            connection.start();
            //创建会话工厂
            Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
            //创建主题
            Destination destination = session.createTopic("myblog_topic");
            MessageConsumer consumer = session.createConsumer(destination);
            //监听消息
            while (true) {
                TextMessage textMessage = (TextMessage) consumer.receive();
                if (textMessage != null) {
                    String text = textMessage.getText();
                    System.out.println("消费者获取消息：" + text);
                } else {
                    break;
                }
            }
            System.out.println("消费者消费消息完毕");

        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

}
